<?php

namespace Georgie\PhpRbac;

use think\db\Query;
use think\Exception;
use think\facade\Db;

class CreateTable
{
    protected $tableKey = 'role';

    //db为数据库配置项默认为空则为默认数据库, cover是否强制覆盖
    public function create($prefix = 'rbac_', $db = '', $cover = false)
    {
        $dbConfig = Db::getConfig();
        if (count($dbConfig) < 1) {
            echo '请配置DB配置';
            exit;
        }

        $hasTable = Db::query('SHOW TABLES LIKE ' . "'" . $prefix . $this->tableKey . "'");
        if ($hasTable && $cover == false) {
            echo "<b style='color:red'>相关数据库表已经存在，如需替换请改为执行 coverCreateTable 方法</b>";
            exit;
        }

        //执行表
        if ($this->_runSql($prefix) === false) {
            echo '执行sql语句出错，请检查配置';
            exit;
        }

        echo "执行成功, <b style='color:red'>非必要请不要再次执行</b>，重复执行会覆盖并清空原有rbac相关表";
    }

    protected function _runSql($prefix)
    {
        $sql = $this->_loadSql();
        $prefix = empty($prefix) ? '' : $prefix;
        $sql = str_replace('###', $prefix, $sql);
        $sqlArr = explode(';', $sql);
        Db::startTrans();
        try {
            foreach ($sqlArr as $value) {
                if ($value !== '')
                    Db::query($value);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
        return true;
    }

    protected
    function _loadSql()
    {
        $fileUrl = __DIR__ . '/rbac.sql';
        $fileObj = fopen($fileUrl, 'r');
        $sql = fread($fileObj, filesize($fileUrl));
        fclose($fileObj);
        return $sql;
    }
}